<template>
  <div>
    <van-field
      v-model="fieldValue"
      is-link
      readonly
      :label="label"
      :placeholder="placeholder"
      @click="showPicker = true"
    />
    <van-popup v-model:show="showPicker" round position="bottom">
      <van-picker
        :columns="columns"
        :columns-field-names="customFieldName"
        cancel-button-text="清空"
        @cancel="onCancel"
        @confirm="onConfirm"
      />
    </van-popup>
  </div>
</template>

<script setup lang="ts" name="SelectPicker">
import { ref } from "vue";

const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  },
  label: {
    type: String,
    default: ""
  },
  placeholder: {
    type: String,
    default: "请选择"
  },
  columns: {
    type: Array,
    default: () => []
  },
  customFieldName: {
    type: Object,
    default: () => {
      return {
        text: "dictLabel",
        value: "dictValue",
        children: "sysDictDataVoList"
      };
    }
  }
});
const emits = defineEmits(["update:modelValue"]);

const fieldValue = ref(props.modelValue);
const showPicker = ref(false);

function onConfirm(val: any) {
  const text = props.customFieldName.text;
  const value = props.customFieldName.value;
  fieldValue.value = val ? val.selectedOptions[0][text] : "";

  const selectValue = val ? val.selectedOptions[0][value] : "";
  emits("update:modelValue", selectValue);
  showPicker.value = false;
}

function onCancel() {
  fieldValue.value = "";
  emits("update:modelValue", "");
  showPicker.value = false;
}
</script>

<style scoped></style>
